import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'ota_upgrade_status.dart';
import 'user_action_type.dart';
import 'package:http/http.dart' as http;

// 用户操作回调
typedef UserActionCallback = Future<void> Function(UserActionType action);

// 状态回调
typedef OtaStatusCallback = void Function(OtaUpgradeStatus status);
typedef ProgressCallback = void Function(double progress, int currentPosition);
typedef TotalSizeCallback = void Function(int totalSize);
typedef UserActionRequiredCallback = void Function(UserActionType action);

class OtaUpgradeManager {
  // 固件下载URL
  final String firmwareUrl;
  // 固件下载请求头
  final Map<String, String>? requestHeaders;
  // 请求方式
  final String? httpMethod;
  // 请求正确的code
  final int? successStatusCode;
  // 总大小回调
  final TotalSizeCallback? onTotalSize;
  // 进度回调
  final ProgressCallback onProgress;
  // 状态回调
  final OtaStatusCallback onStatus;
  // 用户操作回调
  final UserActionRequiredCallback onUserActionRequired;
  // 数据发送回调
  final Future<bool> Function(Uint8List bytes) sendData;

  // 可选的 http client（便于测试注入）
  final http.Client? httpClient;
  // 可选的预置固件数据（便于测试跳过网络下载）
  final Uint8List? initialFirmwareData;
  // 用于模拟升级的步数（便于测试加速）
  final int upgradeSimulationSteps;
  // 每步的持续时间（便于测试加速）
  final Duration upgradeStepDuration;

  // 内部状态
  OtaUpgradeStatus _currentStatus = OtaUpgradeStatus.idle;
  int _totalSize = 0;
  int _currentPosition = 0;
  Uint8List? _firmwareData;
  bool _isPaused = false;
  bool _isCancelled = false;
  int _packetSize = 512; // 默认分包大小
  int _retryCount = 0;
  final int _maxRetryCount = 3;

  // 取消令牌
  final Completer<void> _cancelCompleter = Completer<void>();

  // 流控制器
  final StreamController<OtaUpgradeStatus> _statusController =
      StreamController<OtaUpgradeStatus>.broadcast();

  OtaUpgradeManager({
    required this.firmwareUrl,
    this.requestHeaders,
    this.httpMethod,
    this.successStatusCode,
    required this.onProgress,
    required this.onStatus,
    required this.onUserActionRequired,
    required this.sendData,
    this.onTotalSize,
    this.httpClient,
    this.initialFirmwareData,
    this.upgradeSimulationSteps = 50,
    this.upgradeStepDuration = const Duration(milliseconds: 100),
  });

  OtaUpgradeStatus get currentStatus => _currentStatus;
  bool get isInProgress =>
      _currentStatus.index >= OtaUpgradeStatus.downloadingFirmware.index &&
      _currentStatus.index <= OtaUpgradeStatus.upgrading.index;
  bool get canBeCancelled =>
      isInProgress && _currentStatus != OtaUpgradeStatus.cancelled;

  Stream<OtaUpgradeStatus> get statusStream => _statusController.stream;

  // 更新状态
  void _updateStatus(OtaUpgradeStatus newStatus) {
    // 即便处于取消中，也要允许发布 cancelled 状态；其他状态在取消后不再发布
    if (_currentStatus != newStatus &&
        (!_isCancelled || newStatus == OtaUpgradeStatus.cancelled)) {
      _currentStatus = newStatus;
      _statusController.add(newStatus);
      onStatus(newStatus);
    }
  }

  // 开始升级流程
  Future<void> startUpgrade() async {
    if (_currentStatus != OtaUpgradeStatus.idle) {
      throw StateError('OTA upgrade is already in progress or was cancelled');
    }

    _resetCancellation(); // 重置取消状态

    try {
      await _downloadFirmware();
      if (_checkCancelled()) return;

      await _transferFirmware();
      if (_checkCancelled()) return;

      await _waitForUpgradeCompletion();
    } catch (e) {
      if (!_isCancelled) {
        _handleError(e);
      }
    }
  }

  // 暂停传输
  void pauseTransfer() {
    if (_currentStatus == OtaUpgradeStatus.transferring && !_isCancelled) {
      _isPaused = true;
      _updateStatus(OtaUpgradeStatus.transferPaused);
    }
  }

  // 恢复传输
  void resumeTransfer() {
    if (_currentStatus == OtaUpgradeStatus.transferPaused &&
        _firmwareData != null &&
        !_isCancelled) {
      _isPaused = false;
      _transferFirmwareFromPosition(_currentPosition);
    }
  }

  // 取消升级 - 主要入口
  Future<void> cancelUpgrade() async {
    if (!canBeCancelled) return;

    _isCancelled = true;
    _isPaused = false;

    // 触发取消完成
    if (!_cancelCompleter.isCompleted) {
      _cancelCompleter.complete();
    }

    _updateStatus(OtaUpgradeStatus.cancelled);

    // 延迟重置状态，确保所有操作都已完成
    await Future.delayed(const Duration(milliseconds: 100));
    _resetState();
  }

  // 检查是否已取消
  bool _checkCancelled() {
    return _isCancelled;
  }

  // 等待取消或超时
  Future<void> _waitForCancellationOrTimeout(Duration timeout) async {
    try {
      await _cancelCompleter.future.timeout(timeout);
    } on TimeoutException {
      // 超时继续执行
    }
  }

  // 重置取消状态
  void _resetCancellation() {
    if (_isCancelled) {
      _isCancelled = false;
      _cancelCompleter.complete(); // 完成旧的completer
      // 创建新的completer
      _cancelCompleter
        ..complete()
        ..future.ignore(); // 重置completer
    }
  }

  // 处理用户操作完成
  Future<void> onUserActionCompleted(UserActionType action) async {
    if (_checkCancelled()) return;

    switch (action) {
      case UserActionType.restartDevice:
        await _handleDeviceRestart();
        break;
      case UserActionType.confirmUpgrade:
        await _handleUpgradeConfirmation();
        break;
      case UserActionType.retryTransfer:
        await _retryTransfer();
        break;
      case UserActionType.none:
        break;
    }
  }

  // 下载固件
  Future<void> _downloadFirmware() async {
    _updateStatus(OtaUpgradeStatus.downloadingFirmware);

    // 如果提供了预置固件数据，则跳过网络下载（便于测试）
    if (initialFirmwareData != null) {
      _firmwareData = initialFirmwareData;
      _totalSize = _firmwareData!.length;

      onTotalSize?.call(_totalSize);
      _updateStatus(OtaUpgradeStatus.downloadSuccess);
      return;
    }

    try {
      final client = httpClient ?? http.Client();
      final request = http.Request(httpMethod ?? 'GET', Uri.parse(firmwareUrl));
      if (requestHeaders != null) {
        request.headers.addAll(requestHeaders!);
      }
      final streamedResponse = await client.send(request);

      if (streamedResponse.statusCode != (successStatusCode ?? 200)) {
        throw HttpException(
            'Download failed with status: ${streamedResponse.statusCode}');
      }

      // 使用流式处理，支持取消
      final bytesBuilder = BytesBuilder();
      await for (var chunk in streamedResponse.stream) {
        if (_checkCancelled()) {
          client.close();
          return;
        }
        bytesBuilder.add(chunk);
      }

      _firmwareData = bytesBuilder.toBytes();
      _totalSize = _firmwareData!.length;

      onTotalSize?.call(_totalSize);
      _updateStatus(OtaUpgradeStatus.downloadSuccess);
    } catch (e) {
      if (!_checkCancelled()) {
        _updateStatus(OtaUpgradeStatus.downloadFailed);
        rethrow;
      }
    }
  }

  // 传输固件
  Future<void> _transferFirmware() async {
    if (_firmwareData == null) {
      throw StateError('Firmware data is not available');
    }

    if (_checkCancelled()) return;

    _updateStatus(OtaUpgradeStatus.transferring);
    await _transferFirmwareFromPosition(0);
  }

  // 从指定位置开始传输
  Future<void> _transferFirmwareFromPosition(int startPosition) async {
    _currentPosition = startPosition;
    _retryCount = 0;

    while (_currentPosition < _totalSize && !_checkCancelled()) {
      if (_isPaused) {
        await _waitForCancellationOrTimeout(const Duration(milliseconds: 100));
        continue;
      }

      final endPosition = _calculateEndPosition(_currentPosition);
      final packet = _firmwareData!.sublist(_currentPosition, endPosition);

      final success = await _sendPacketWithRetry(packet);

      if (!success) {
        if (!_checkCancelled()) {
          _updateStatus(OtaUpgradeStatus.transferFailed);
          onUserActionRequired(UserActionType.retryTransfer);
        }
        return;
      }

      _currentPosition = endPosition;
      final progress = _currentPosition / _totalSize;
      onProgress(progress, _currentPosition);

      // 添加小延迟避免阻塞，但检查取消
      await _waitForCancellationOrTimeout(const Duration(milliseconds: 10));
    }

    if (!_checkCancelled() && _currentPosition >= _totalSize) {
      _updateStatus(OtaUpgradeStatus.transferSuccess);
    }
  }

  // 计算数据包结束位置
  int _calculateEndPosition(int start) {
    return (start + _packetSize).clamp(0, _totalSize);
  }

  // 带重试的数据包发送
  Future<bool> _sendPacketWithRetry(Uint8List packet) async {
    while (_retryCount < _maxRetryCount && !_checkCancelled()) {
      try {
        final success = await sendData(packet);
        if (success) {
          _retryCount = 0;
          return true;
        }
      } catch (e) {
        print('Packet send error: $e');
      }

      _retryCount++;
      if (_retryCount < _maxRetryCount && !_checkCancelled()) {
        await _waitForCancellationOrTimeout(const Duration(milliseconds: 100));
      }
    }

    return false;
  }

  // 等待升级完成
  Future<void> _waitForUpgradeCompletion() async {
    if (_checkCancelled()) return;

    _updateStatus(OtaUpgradeStatus.waitingUserAction);
    onUserActionRequired(UserActionType.restartDevice);
  }

  // 处理设备重启
  Future<void> _handleDeviceRestart() async {
    if (_checkCancelled()) return;

    _updateStatus(OtaUpgradeStatus.upgrading);

    // 模拟升级过程，实际应用中可能需要等待设备响应
    for (int i = 0; i < upgradeSimulationSteps; i++) {
      // 分成多步，每步可配置持续时间，便于测试加速和取消检查
      if (_checkCancelled()) return;
      await _waitForCancellationOrTimeout(upgradeStepDuration);
    }

    // 检查升级结果
    if (!_checkCancelled()) {
      final success = await _verifyUpgrade();

      if (success) {
        _updateStatus(OtaUpgradeStatus.upgradeSuccess);
      } else {
        _updateStatus(OtaUpgradeStatus.upgradeFailed);
      }
    }
  }

  // 处理升级确认
  Future<void> _handleUpgradeConfirmation() async {
    if (_checkCancelled()) return;
    // 实现升级确认后的逻辑
  }

  // 重试传输
  Future<void> _retryTransfer() async {
    if (_checkCancelled()) return;
    await _transferFirmwareFromPosition(_currentPosition);
  }

  // 验证升级结果
  Future<bool> _verifyUpgrade() async {
    if (_checkCancelled()) return false;

    // 实现升级验证逻辑
    // 这里可以发送验证命令到设备并检查响应
    try {
      final verificationPacket =
          Uint8List.fromList([0x01, 0x02, 0x03]); // 示例验证包
      return await sendData(verificationPacket);
    } catch (e) {
      return false;
    }
  }

  // 处理错误
  void _handleError(dynamic error) {
    if (_checkCancelled()) return;

    print('OTA Upgrade Error: $error');

    switch (_currentStatus) {
      case OtaUpgradeStatus.downloadingFirmware:
        _updateStatus(OtaUpgradeStatus.downloadFailed);
        break;
      case OtaUpgradeStatus.transferring:
        _updateStatus(OtaUpgradeStatus.transferFailed);
        break;
      default:
        _updateStatus(OtaUpgradeStatus.upgradeFailed);
    }
  }

  // 重置状态
  void _resetState() {
    _currentPosition = 0;
    _totalSize = 0;
    _firmwareData = null;
    _isPaused = false;
    _retryCount = 0;
  }

  // 释放资源
  void dispose() {
    if (!_cancelCompleter.isCompleted) {
      _cancelCompleter.complete();
    }
    _statusController.close();
    _resetState();
  }
}
